﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
/**
    public class ViewModelLocator 
    { 
        private static NavigationController _navController;
        public static void Init(PhoneApplicationFrame frame) 
        { 
            _navController = new NavigationController(frame); 
        } 
    }
 * 在App的构造方法中
 * ViewModelLocator.Init(RootFrame);
 * */

namespace Code4WP7SDK
{
    public class NavigationController
    {
        private INavigationBase _currentViewModel; //当前页面的ViewModel

        public NavigationController(PhoneApplicationFrame frame)
        {
            frame.Navigated += frame_Navigated;
            frame.Navigating += frame_Navigating;
            frame.NavigationFailed += frame_NavigationFailed;
            frame.NavigationStopped += frame_NavigationStopped;
        }

        void frame_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if (_currentViewModel != null)
            {
                if (_currentViewModel is IBaseNavigatedModel)
                {
                    ((IBaseNavigatedModel)_currentViewModel).OnNavigatedFrom(e);
                }
                _currentViewModel = null;
            }

            var page = e.Content as PhoneApplicationPage;
            if (page != null && page.DataContext is INavigationBase)
            {
                _currentViewModel = (INavigationBase)page.DataContext;
                if (_currentViewModel is IBaseNavigatedModel)
                {
                    ((IBaseNavigatedModel)_currentViewModel).OnNavigatedTo(e);
                }
            }
        }

        void frame_Navigating(object sender, System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            if (_currentViewModel is IBaseNavigatingModel)
            {
                ((IBaseNavigatingModel)_currentViewModel).OnNavigatingFrom(e);
            }
        }

        void frame_NavigationFailed(object sender, System.Windows.Navigation.NavigationFailedEventArgs e)
        {
            if (_currentViewModel is IBaseNavigatedModel)
            {
                ((IBaseNavigatedModel)_currentViewModel).OnNavigationFailed(e);
            }
        }

        void frame_NavigationStopped(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if (_currentViewModel is IBaseNavigatedModel)
            {
                ((IBaseNavigatedModel)_currentViewModel).OnNavigationStopped(e);
            }
        }
    }

}
